import 'dart:ui';
import 'package:canteen/class/order.dart';
import 'package:canteen/dio/order_dio.dart';
import 'package:canteen/dio/pR_dio.dart';
import 'package:canteen/dio/set_meal_dio.dart';
import 'package:canteen/history_c_v.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:canteen/page/add_PR.dart';
import 'package:canteen/page/choose_pR_page.dart';
import 'package:canteen/page/history_page.dart';
import 'package:canteen/page/init_page.dart';
import 'package:canteen/page/manage_staff_page.dart';
import 'package:canteen/page/menu_page.dart';
import 'package:canteen/userDetail.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:canteen/component/gradient_painter.dart';
import 'package:canteen/dio/configure_dio.dart';
import 'package:canteen/dio/dish_dio.dart';
import 'package:canteen/dio/category_dio.dart';
import 'package:canteen/class/dish.dart';
import 'package:canteen/class/ingredient.dart';
import 'package:canteen/class/set_meal.dart';
import 'package:canteen/menu_c_v.dart';

import '../class/user.dart';
import '../dio/user_dio.dart';
import '../method/showDialog.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  static const String id = 'home_page';

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String date = '${DateTime.now().toString().substring(0, 10)}';
  String greeting = '';

  @override
  void initState() {
    super.initState();
    getHello();
    getData();
  }

  void getHello() {
    int timeInHour = int.parse(DateTime.now().toString().substring(11, 13));
    if (timeInHour < 12) {
      greeting = 'Good\nmorning .';
    } else if (timeInHour < 18) {
      greeting = 'Good\nafternoon .';
    } else {
      greeting = 'Good\nevening .';
    }
  }

  Map<Ingredient, double> getIngredients(components) {
    if (components == '') {
      return {};
    }
    Map<Ingredient, double> Ingredients = {};
    components.split('#').forEach((element) {
      List component = element.split(' ');
      Ingredient ingredient = Ingredient(
          unit: component[3], name: component[1], type: component[0]);
      Ingredients.addEntries(
          [MapEntry(ingredient, double.parse(component[2]))]);
    });
    return Ingredients;
  }

  Map<Dish, int> getDishes(components) {
    Map<Dish, int> dishes = {};
    for (var element in components.keys) {
      dishes.addEntries(
          [MapEntry(findDishByName(element, allDishes)!, components[element])]);
    }
    return dishes;
  }

  Future<void> getDishSetMealOrder() async {
    Response dishResponse = await getAllDishes(dio: dio);
    List<dynamic> dishData = dishResponse.data['data'];
    for (var element in dishData) {
      dishesWithCategory[element['categoryName']]?.add(Dish(
          id: element['id'],
          name: element['name'],
          components: getIngredients(element['components']),
          category: element['categoryName']));
    }
    dishesWithCategory.forEach((key, value) {
      allDishes.addAll(value);
    });
    Response setMealResponse = await getAllSetMeals(dio: dio);
    List<dynamic> setMealData = setMealResponse.data['data'];
    for (var element in setMealData) {
      setMealsWithCategory[element['categoryName']]?.add(SetMeal(
          id: element['id'],
          name: element['name'],
          dishes: getDishes(element['dishCount']),
          category: element['categoryName']));
    }
    setMealsWithCategory.forEach((key, value) {
      allSetMeals.addAll(value);
    });
    Response orderResponse = await getAllOrders(dio: dio);
    List<dynamic> orderData = orderResponse.data['data'];
    for (var element in orderData) {
      List time = element['date'].split(' ');
      if (ordersWithDate[time[0]] == null) {
        ordersWithDate[time[0]] = {};
      }
      (ordersWithDate[time[0]]![time[1]] ??= []).add(Order(
        dishes: getDishes(element['dishCount']),
        setMeals: getSetMeals(element['setMealCount']),
        pRoom: element['privateRoomName'],
        id: element['id'],
        name: element['name'],
      ));
    }
  }

  Map<SetMeal, int> getSetMeals(components) {
    Map<SetMeal, int> setMeals = {};
    for (var element in components.keys) {
      setMeals.addEntries([
        MapEntry(findSetMealByName(element, allSetMeals)!, components[element])
      ]);
    }
    return setMeals;
  }

  Future<void> getCategory() async {
    Response categoryResponse = await getAllCategories(dio: dio);
    List<dynamic> categoryData = categoryResponse.data['data'];
    for (var element in categoryData) {
      dishesWithCategory.addEntries([MapEntry(element['name'], [])]);
      setMealsWithCategory.addEntries([MapEntry(element['name'], [])]);
      categoryId.addEntries([MapEntry(element['name'], element['id'])]);
    }
  }

  void refreshData() {
    dishesWithCategory.clear();
    setMealsWithCategory.clear();
    categoryId.clear();
    allSetMeals.clear();
    allDishes.clear();
    allStaffs.clear();
    privateRooms.clear();
    ordersWithDate.clear();
  }

  Future<void> getData() async {
    int maxRetries = 3;
    const Duration retryDelay = Duration(seconds: 2); // 设置重试间隔时间为2秒

    bool categorySuccess = false;
    bool dishSuccess = false;
    bool roomsSuccess = false;
    refreshData();
    Future<void> retry() async {
      try {
        if (!categorySuccess) {
          await getCategory();
          categorySuccess = true;
        }
      } catch (e) {
        print('Category error during operation: $e');
      }
      try {
        if (!dishSuccess) {
          await getDishSetMealOrder();
          dishSuccess = true;
        }
      } catch (e) {
        print('Dish error during operation: $e');
      }
      try {
        if (!roomsSuccess) {
          await getPrivateRooms();
          roomsSuccess = true;
        }
      } catch (e) {
        print('Room error during operation: $e');
      }
      if (categorySuccess && dishSuccess && roomsSuccess) {
        sortData();
      } else {
        if (maxRetries == 0) {
          return;
        }
        maxRetries--;
        await Future.delayed(retryDelay);
        await retry();
      }
    }

    await retry();
    getAllStaffs();
    getDepartments();
  }

  sortData() {
    privateRooms.sort((a, b) => a.compareTo(b));
    getSortedCategory();
    dishesWithCategory.forEach((key, value) {
      value.sort((a, b) => a.name.compareTo(b.name));
    });
    setMealsWithCategory.forEach((key, value) {
      value.sort((a, b) => a.name.compareTo(b.name));
    });
    ordersWithDate.forEach((key, value) {
      value.forEach((key, value1) {
        value1.sort((a, b) => a.pRoom.compareTo(b.pRoom));
      });
    });
  }

  void getSortedCategory() async {
    sortedCategory = dishesWithCategory.keys.toList();
    sortedCategory.sort((a, b) => a.compareTo(b));
  }

  void getDepartments() {
    departments = dishesWithCategory.keys.toList();
    departments.removeWhere((element) {
      if (setMealsWithCategory[element] != null) {
        if (setMealsWithCategory[element]!.isNotEmpty) {
          return true;
        }
        return false;
      } else {
        return false;
      }
    });
  }

  Future<void> getAllStaffs() async {
    try {
      Response response = await getAllUsers(dio: dio);
      dynamic data = response.data['data'];
      allStaffs.clear();
      for (var element in data) {
        allStaffs.add(
          User(
            id: element['id'],
            username: element['username'],
            password: element['password'],
            type: element['type'],
            department: element['department'] ?? '无',
          ),
        );
      }
      setState(() {});
    } on Exception catch (e) {
      ShowDialog.showError(context);
    }
  }

  Future<void> getPrivateRooms() async {
    Response response = await getAllPR(dio: dio);
    dynamic privateRoomData = response.data['data'];
    for (var element in privateRoomData) {
      privateRooms.add(element['name']);
    }
  }

  Future<void> reFetchData() async {
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return user.type == 'GUEST'
        ? GestureDetector(
            onTap: () {
              Navigator.pushReplacementNamed(context, InitPage.id);
            },
            child: Container(
              alignment: Alignment.center,
              color: Colors.black,
              child: Text(
                '你没有访问权限,请离开!',
                style: TextStyle(color: Colors.white, fontSize: 32),
              ),
            ),
          )
        : Scaffold(
            backgroundColor: Color(0xFFffffff),
            body: Stack(
              children: [
                // 渐变色背景
                Positioned.fill(
                  child: CustomPaint(
                    painter: GradientPainter(
                        colorList: [
                          Color(0xffF9FF9F),
                          Color(0xff95FFB1),
                          Color(0xff9ED7FF),
                          Color(0xffEA83FF),
                        ].map((e) => e.withOpacity(0.8)).toList(),
                        xS: 0,
                        yS: 0,
                        heightMul: 0.3),
                  ),
                ),
                Positioned.fill(
                  child: CustomPaint(
                    painter: GradientPainter(
                        colorList: [
                          Color(0xffE4EEFA),
                          Color(0xff9ED7FF),
                        ].map((e) => e.withOpacity(0.8)).toList(),
                        xS: 0,
                        yS: MediaQuery.of(context).size.height - 90,
                        heightMul: 0.15),
                  ),
                ),
                BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 1000, sigmaY: 60),
                  child: Container(),
                ),
                Positioned(
                  left: 80,
                  bottom: 40,
                  child: Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                    ),
                  ),
                ),
                BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                  child: Container(),
                ),
                Container(
                  margin: EdgeInsets.only(
                      left: 30,
                      right: 30,
                      top: 20,
                      bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: RefreshIndicator(
                    color: Color(0xff6486f3),
                    onRefresh: reFetchData,
                    child: ListView(
                      children: [
                        SizedBox(
                          height: 160,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                height: 30,
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    greeting,
                                    style: TextStyle(
                                        fontSize: 32,
                                        fontWeight: FontWeight.bold),
                                    softWrap: true,
                                  ),
                                  GestureDetector(
                                    onLongPress: () {
                                      Navigator.pushNamedAndRemoveUntil(context,
                                          InitPage.id, (route) => false);
                                    },
                                    onTap: () {
                                      if (user.type != 'SUPERADMIN') {
                                        return;
                                      }
                                      Navigator.pushNamed(
                                          context, ManageStaffPage.id);
                                    },
                                    child: Container(
                                      clipBehavior: Clip.hardEdge,
                                      width: 35,
                                      height: 35,
                                      decoration:
                                          BoxDecoration(shape: BoxShape.circle),
                                      child: Image.asset('images/photo1.jpg'),
                                    ),
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: 110,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Icon(Icons.brightness_1_outlined),
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Icon(Icons.brightness_2_outlined),
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Icon(Icons.cloud_queue_rounded),
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Icon(
                                    Icons.water_drop_outlined,
                                  )
                                ],
                              ),
                              SizedBox(
                                height: 15,
                              ),
                              Text(
                                'now--> $date',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 13),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: MediaQuery.of(context).size.height - 394 > 400
                              ? MediaQuery.of(context).size.height - 394
                              : 400,
                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment:
                                      CrossAxisAlignment.stretch,
                                  children: [
                                    Expanded(
                                      flex: 2,
                                      child: GestureDetector(
                                        onTap: () {
                                          Navigator.of(context)
                                              .pushNamed(ChoosePRPage.id);
                                        },
                                        child: Container(
                                          clipBehavior: Clip.hardEdge,
                                          margin: EdgeInsets.only(
                                              right: 8, bottom: 16),
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(15),
                                              color: Color(0xffFFC58E)),
                                          child: Stack(
                                            children: [
                                              Positioned(
                                                left: 35,
                                                bottom: -40,
                                                child: Icon(
                                                  Icons.cloud,
                                                  color: Color(0xffFFE8D1),
                                                  size: 140,
                                                ),
                                              ),
                                              Positioned(
                                                bottom: -30,
                                                child: Icon(
                                                  Icons.cloud,
                                                  color: Color(0xffFFD7B0),
                                                  size: 140,
                                                ),
                                              ),
                                              Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    children: [
                                                      Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .only(
                                                                left: 15.0,
                                                                top: 20),
                                                        child: Text(
                                                          '订单',
                                                          style: TextStyle(
                                                              fontSize: 15,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.end,
                                                    children: [
                                                      Container(
                                                        width: 45,
                                                        height: 45,
                                                        margin: EdgeInsets.only(
                                                            right: 15,
                                                            bottom: 20),
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(15),
                                                          color:
                                                              Color(0xffFFC58E),
                                                        ),
                                                        child: Icon(Icons
                                                            .cloud_queue_rounded),
                                                      )
                                                    ],
                                                  )
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 3,
                                      child: GestureDetector(
                                        onTap: () {
                                          if (user.type == 'ADMIN' ||
                                              user.type == 'SUPERADMIN') {
                                            Navigator.of(context)
                                                .pushNamed(MenuPage.id);
                                          }
                                          // else{
                                          //   ShowDialog.showErrorAndDetail(context, '你没有权限进入');
                                          // }
                                        },
                                        child: Container(
                                          clipBehavior: Clip.hardEdge,
                                          margin: EdgeInsets.only(right: 8),
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(15),
                                              color: Color(0xffD690FF)),
                                          child: Stack(
                                            children: [
                                              Positioned(
                                                left: 35,
                                                bottom: -30,
                                                child: Icon(
                                                  Icons.brightness_2,
                                                  color: Color(0xffF3DDFF),
                                                  size: 140,
                                                ),
                                              ),
                                              Positioned(
                                                bottom: -20,
                                                child: Icon(
                                                  Icons.brightness_2,
                                                  color: Color(0xffE7BBFF),
                                                  size: 140,
                                                ),
                                              ),
                                              Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    children: [
                                                      Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .only(
                                                                left: 15.0,
                                                                top: 20),
                                                        child: Text(
                                                          '菜单',
                                                          style: TextStyle(
                                                              fontSize: 15,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.end,
                                                    children: [
                                                      Container(
                                                        width: 45,
                                                        height: 45,
                                                        margin: EdgeInsets.only(
                                                            right: 15,
                                                            bottom: 20),
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(15),
                                                          color:
                                                              Color(0xffD690FF),
                                                        ),
                                                        child: Icon(Icons
                                                            .brightness_2_outlined),
                                                      )
                                                    ],
                                                  )
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment:
                                      CrossAxisAlignment.stretch,
                                  children: [
                                    Expanded(
                                      flex: 3,
                                      child: GestureDetector(
                                        onTap: () {
                                          Navigator.pushNamed(
                                              context, HistoryPage.id);
                                        },
                                        child: Container(
                                          clipBehavior: Clip.hardEdge,
                                          margin: EdgeInsets.only(
                                              left: 8, bottom: 16),
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(15),
                                              color: Color(0xff9FF4FF)),
                                          child: Stack(
                                            children: [
                                              Positioned(
                                                left: 25,
                                                bottom: -40,
                                                child: Icon(
                                                  Icons.brightness_1,
                                                  color: Color(0xffDEFBFF),
                                                  size: 140,
                                                ),
                                              ),
                                              Positioned(
                                                left: -10,
                                                bottom: -30,
                                                child: Icon(
                                                  Icons.brightness_1,
                                                  color: Color(0xffC0F7FF),
                                                  size: 140,
                                                ),
                                              ),
                                              Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    children: [
                                                      Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .only(
                                                                left: 15.0,
                                                                top: 20),
                                                        child: Text(
                                                          '历史',
                                                          style: TextStyle(
                                                              fontSize: 15,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.end,
                                                    children: [
                                                      Container(
                                                        width: 45,
                                                        height: 45,
                                                        margin: EdgeInsets.only(
                                                            right: 15,
                                                            bottom: 20),
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(15),
                                                          color:
                                                              Color(0xff9FF4FF),
                                                        ),
                                                        child: Icon(Icons
                                                            .brightness_1_outlined),
                                                      )
                                                    ],
                                                  )
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 2,
                                      child: GestureDetector(
                                        onTap: () {
                                          if (user.type == 'ADMIN' ||
                                              user.type == 'SUPERADMIN') {
                                            Navigator.pushNamed(
                                                context, AddPR.id);
                                          }
                                        },
                                        child: Container(
                                          clipBehavior: Clip.hardEdge,
                                          margin: EdgeInsets.only(left: 8),
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(15),
                                              color: Color(0xffAEE998)),
                                          child: Stack(
                                            children: [
                                              Positioned(
                                                left: 35,
                                                bottom: -40,
                                                child: Icon(
                                                  Icons.water_drop_rounded,
                                                  color: Color(0xffCEF4C1),
                                                  size: 140,
                                                ),
                                              ),
                                              Positioned(
                                                bottom: -30,
                                                child: Icon(
                                                  Icons.water_drop_rounded,
                                                  color: Color(0xffC4EEB5),
                                                  size: 140,
                                                ),
                                              ),
                                              Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    children: [
                                                      Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .only(
                                                                left: 15.0,
                                                                top: 20),
                                                        child: Text(
                                                          '包房',
                                                          style: TextStyle(
                                                              fontSize: 15,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.end,
                                                    children: [
                                                      Container(
                                                        width: 45,
                                                        height: 45,
                                                        margin: EdgeInsets.only(
                                                            right: 15,
                                                            bottom: 20),
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(15),
                                                          color:
                                                              Color(0xffAEE998),
                                                        ),
                                                        child: Icon(Icons
                                                            .water_drop_outlined),
                                                      )
                                                    ],
                                                  )
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
  }
}
// Positioned(
//   bottom: 0,
//   left: 0,
//   right: 0,
//   child: Container(
//     padding: EdgeInsets.symmetric(horizontal: 30),
//     height: 100,
//     decoration: BoxDecoration(
//       color: Colors.white,
//       borderRadius: BorderRadius.only(
//         topLeft: Radius.circular(25),
//         topRight: Radius.circular(25),
//       ),
//     ),
//     child: Row(
//       mainAxisAlignment: MainAxisAlignment.spaceBetween,
//       children: [
//         Text(
//           '查看订单',
//           style: TextStyle(fontSize: 20),
//         ),
//         Icon(
//           Icons.keyboard_arrow_up_rounded,
//           size: 70,
//         )
//       ],
//     ),
//   ),
// ),
// SizedBox(
// height: 50,
// ),
// Container(
// padding:
// EdgeInsets.symmetric(horizontal: 30, vertical: 15),
// height: 140,
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(8),
// color: Colors.white,
// boxShadow: [
// BoxShadow(
// color: Colors.black.withOpacity(0.1),
// offset: Offset(2, 2),
// blurRadius: 8,
// spreadRadius: 2,
// )
// ]),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Text(
// '已备原材料',
// style: TextStyle(fontSize: 20),
// ),
// Row(
// children: [
// Text(
// date,
// style: TextStyle(
// fontSize: 16,
// fontWeight: FontWeight.bold),
// ),
// Icon(Icons.keyboard_arrow_down_rounded)
// ],
// )
// ],
// ),
// SizedBox(
// height: 85,
// width: 85,
// child: GradientProgressIndicator(
// progress: 0.7,
// )),
// ],
// ),
// ),
